package cn.com.b2office.dao.hibernate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.com.b2office.dao.MemberDao;
import cn.com.b2office.domain.ExData;
import cn.com.b2office.domain.Member;
import cn.com.b2office.domain.MemberAddress;
import cn.com.b2office.domain.Sequence;
import cn.com.b2office.exchange.ClassMapping;
import cn.com.b2office.util.MD5;

public class MemberDaoHibernateImpl extends HibernateDaoSupport implements
		MemberDao {

	private static final String ADDRESS_SEQUENCE = "ADDRESS";

	private static final String MEMBER_SEQUENCE = "MEMBER";

	private SimpleDateFormat df = new SimpleDateFormat("yyMMdd");

	public String createAddress(MemberAddress address) {
		if (address.getAddidno() == null
				|| address.getAddidno().trim().equals("")) {
			String addressId = getSequenceId(ADDRESS_SEQUENCE, 4);
			address.setAddidno(addressId);
		}
		Session s = getSession();
		try {
			s.save(address);
			//
			ExData data = new ExData();
			data.setEntity(ClassMapping.getClassCode(MemberAddress.class));
			data.setEntityId(address.getAddidno());
			data.setOperation(ExData.INSERT);
			data.setModifytime(new Date());
			s.save(data);
			s.flush();
		} catch (RuntimeException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
		return address.getAddidno();
	}

	public String createMember(Member member) {
		if (member.getMemberid() == null
				|| member.getMemberid().trim().equals("")) {
			String memberId = getSequenceId(MEMBER_SEQUENCE, 4);
			member.setMemberid(memberId);
		}
		Session s = getSession();
		try {
			s.save(member);
			// 增加记录
			ExData data = new ExData();
			data.setEntity(ClassMapping.getClassCode(Member.class));
			data.setEntityId(member.getMemberid());
			data.setOperation(ExData.INSERT);
			data.setModifytime(new Date());
			s.save(data);
			s.flush();
		} catch (RuntimeException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
		return member.getMemberid();
	}

	public Member getMember(String memberId) {
		return (Member) getHibernateTemplate().get(Member.class, memberId);
	}

	@SuppressWarnings("unchecked")
	public MemberAddress getRegAddress(String memberId) {
		List<MemberAddress> list = getHibernateTemplate().find(
				"from MemberAddress where memberid=? and flag=1 and deleted=0",
				memberId);
		if (list == null || list.isEmpty())
			return null;
		return list.get(0);
	}

	@SuppressWarnings("unchecked")
	public List<MemberAddress> listAddresses(String memberId) {
		return getHibernateTemplate().find(
				"from MemberAddress where memberid=? and deleted=0", memberId);
	}

	public void updateAddress(MemberAddress memberAddress) {
		Session s = getSession();
		try {
			s.update(memberAddress);
			// 增加记录
			ExData data = new ExData();
			data.setEntity(ClassMapping.getClassCode(MemberAddress.class));
			data.setEntityId(memberAddress.getAddidno());
			data.setOperation(ExData.UPDATE);
			data.setModifytime(new Date());
			s.save(data);
			s.flush();
		} catch (RuntimeException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
	}

	public void updateMember(Member member) {
		Session s = getSession();
		try {
			s.update(member);
			// 增加记录
			ExData data = new ExData();
			data.setEntity(ClassMapping.getClassCode(Member.class));
			data.setEntityId(member.getMemberid());
			data.setOperation(ExData.UPDATE);
			data.setModifytime(new Date());
			s.save(data);
			s.flush();
		} catch (RuntimeException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
	}

	@SuppressWarnings("unchecked")
	public Member validateTelMember(String memberno, String telPwd) {
		Object[] args = new Object[2];
		args[0] = memberno;
		args[1] = MD5.hash(telPwd);
		List<Member> list = getHibernateTemplate().find(
				"from Member where memberno=? and numpwd=?", args);
		if (list == null || list.isEmpty())
			return null;
		return list.get(0);
	}

	@SuppressWarnings("unchecked")
	public Member validateWebMember(String regName, String regPwd) {
		Object[] args = new Object[2];
		args[0] = regName;
		args[1] = MD5.hash(regPwd);
		List<Member> list = getHibernateTemplate().find(
				"from Member where regname=? and regpwd=?", args);
		if (list == null || list.isEmpty())
			return null;
		return list.get(0);
	}

	/*
	 * 生成不重复序列码
	 */
	public synchronized String getSequenceId(String sequenceName, int num) {
		int id = 0;
		Session s = getSession();
		try {
			Sequence sequence = (Sequence) s.get(Sequence.class, sequenceName);
			if (sequence == null) {
				sequence = new Sequence();
				sequence.setName(sequenceName);
				sequence.setNextId(1);
				s.save(sequence);
				s.flush();
			}
			id = sequence.getNextId();
			// 自增
			sequence.setNextId(id + 1);
			s.save(sequence);
			s.flush();
		} catch (RuntimeException e) {
			logger.error(e.getMessage());
			throw e;
		} finally {
			releaseSession(s);
		}
		return "W" + df.format(new Date()) + buildStr(id, num);
	}

	private String buildStr(int num, int length) {
		String str = String.valueOf(num);
		int strLength = str.length();
		if (strLength >= length)
			return str;
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < length - strLength; i++) {
			sb.append("0");
		}
		sb.append(str);
		return sb.toString();
	}

	public MemberAddress getAddress(String addressId) {
		return (MemberAddress) getHibernateTemplate().get(MemberAddress.class,
				addressId);
	}

	/** return false 注册名不存在,可以注册 ; return true 注册名存在，不能注册 */
	@SuppressWarnings("unchecked")
	public boolean ifRegNameExist(String regName) {
		List<Member> list = getHibernateTemplate().find(
				"from Member where regname=?", regName);
		if (list.size() == 0) {
			return false; // 注册名不存在
		} else {
			return true; // 注册名存在
		}
	}

	/** return false 注册Email不存在,可以注册 ; return true 注册名存在，不能注册 */
	@SuppressWarnings("unchecked")
	public boolean ifRegEmailExist(String regEmail) {
		List<Member> list = getHibernateTemplate().find(
				"from Member where regemail=?", regEmail);
		if (list.size() == 0) {
			return false; // 注册email不存在
		} else {
			return true; // email已经注册过了
		}
	}

	/** 根据email 得到用户信息 */
	@SuppressWarnings("unchecked")
	public Member getMemberByEmail(String regEmail) {
		List<Member> list = getHibernateTemplate().find(
				"from Member where regemail=?", regEmail);
		Member member = list.get(0);
		return member;
	}

	@SuppressWarnings("unchecked")
	public Member getMemberByMemberno(String memberno) {
		List<Member> list = getHibernateTemplate().find(
				"from Member where memberno=?", memberno);
		if (list.size() == 0) {
			return null;
		} else {
			return list.get(0);
		}
	}

	@SuppressWarnings("unchecked")
	public Member getMemberByMembernoAndEmail(String memberno, String email) {
		List<Member> list = getHibernateTemplate().find(
				"from Member where memberno=? and regemail=?",
				new Object[] { memberno, email });
		if (list.size() == 0) {
			return null;
		} else {
			return list.get(0);
		}
	}

	@SuppressWarnings("unchecked")
	public Member getMemberByNameAndEmail(String regName, String email) {
		List<Member> list = getHibernateTemplate().find(
				"from Member where regname=? and regemail=?",
				new Object[] { regName, email });
		if (list.size() == 0) {
			return null;
		} else {
			return list.get(0);
		}
	}

	public void initializeMemberPwd(String memberId, String pwd) {
		Member member = (Member) getHibernateTemplate().load(Member.class,
				memberId);
		member.setRegpwd(pwd);
		updateMember(member);
	}

}
